#include "tinyrpc/net/timerque.h"
#include "tinyrpc/net/eventloop.h"
#include <iostream>
#include "tinyrpc/base/task.h"
#include "tinyrpc/base/thread.h"
#include "tinyrpc/net/coroutine_function.h"
#include "tinyrpc/net/channel/serversocketchannel.h"
#include "tinyrpc/net/inetaddress.h"

using namespace TinyRPC;

// coroutine_sleep 一定要写到协程里面
EventLoop * loop;

void echo_test(SocketChannelPtr socketChannel){
    while (1)
    {
        BufferPtr buffer = socketChannel->read();
        std::string str = buffer->read();
        
        if(str.compare("quit\r\n")==0){
            
            std::cout<<"need quit"<<std::endl;
            return;
            //Coroutine::Yield();
        }
        std::cout<<str<<std::endl;
    }
    
    
}

void accept_test(int port){
    INetAddress address("127.0.0.1", port);
    ServerSocketChannel server = ServerSocketChannel::CreateAndBind(address);
    server.listen();
    SocketChannelPtr socketChannel = nullptr;
    while (1)
    {
        socketChannel = server.accept();
        // loop->runInLoop(Task(std::bind(&TcpServer::echo, this, socketChannel), true));
        std::cout<<"accept socket"<<std::endl;
        // 这里会存在问题， 即在一个协程里面调用另一个协程
        loop->queueInLoop(Task(std::bind(echo_test, socketChannel), true));
        socketChannel.reset();
    }
}

int main(int argc, char ** argv){
    int port = 8081;
    std::cout<<argc<<std::endl;
    if(argc == 2){
        port = atoi(argv[1]);
    }
    EventLoop eventLoop;
    loop = & eventLoop;
    
    eventLoop.runInLoop(Task(std::bind(accept_test, port), true));
    eventLoop.loop();
}